
package com.afd.ozblip.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONObject;

import com.afd.ozblip.adapter.UserSignListAdapter;
import com.afd.ozblip.entity.UserSignDetialEntity;
import com.afd.ozblip.net.HttpUtil;
import com.afd.ozblip.util.AsyncAction;
import com.afd.ozblip.util.AsyncLoadData;
import com.afd.ozblip.util.CollectionUtil;
import com.afd.ozblip.util.Constants;
import com.afd.ozblip.view.SignHistogramGraphView;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.RadioGroup.OnCheckedChangeListener;

public class UserSignedActivity extends BaseActivity {

    public static final String G_KEY = "group_key";
    public static final String G_VAL = "group_val";
    private static final String G_CHILD = "group_child";

    private static final String C_KEY = "child_key";
    private static final String C_VAL = "child_val";
    /****************** 视图变量 **************************/
    private RadioGroup userSignRg;
    private RadioGroup signTotalRg;
    private RadioButton totalTableRb;
    private LinearLayout totalLayout;
    private RelativeLayout detailLayout;
    private LinearLayout tableLayout;
    private ExpandableListView exList;
    private SignHistogramGraphView signHg;
    private ImageView shareChartIv;

    private ListView signDetailLv;

    private TextView tipTv;

    /****************** 数据变量 **************************/
    private String userId;
    private ExAdapter adapter;
    List<Map<String, Object>> signTotalData = new ArrayList<Map<String, Object>>();

    private UserSignListAdapter userSignListAdapter;
    private List<UserSignDetialEntity> userSignList;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.user_signed);
        // 启动返回功能
        toBack();
        // 寻找视图
        findViews();
        // 设置监听
        setListeners();
        // 获取参数
        getBundle();
        // 获取统计数据
        requestUserSignTotalData();
    }

    /**
     * 寻找视图
     */
    public void findViews() {
        this.userSignRg = (RadioGroup) findViewById(R.id.rg_user_sign_tab);
        this.tipTv = (TextView) findViewById(R.id.tv_user_sign_tip);
        this.totalLayout = (LinearLayout) findViewById(R.id.ll_user_sign_total);
        this.detailLayout = (RelativeLayout) findViewById(R.id.rl_user_sign_detail);
        this.signTotalRg = (RadioGroup) findViewById(R.id.rg_user_sign_total_tab);
        this.totalTableRb = (RadioButton) findViewById(R.id.rb_user_sign_table);
        this.tableLayout = (LinearLayout) findViewById(R.id.lv_user_sign_total_table);
        this.signHg = (SignHistogramGraphView) findViewById(R.id.hg_user_sign_chart);
        this.shareChartIv = (ImageView) findViewById(R.id.iv_user_sign_share_ico);
        this.signDetailLv = (ListView) findViewById(R.id.lv_user_sign_detail);
    }

    /**
     * 设置监听
     */
    public void setListeners() {
        View.OnClickListener moreClick = new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                switch (v.getId()) {
                    case R.id.ll_more_layout_setting:
                        Intent settingIntent = new Intent(UserSignedActivity.this,
                                SettingActivity.class);
                        startActivity(settingIntent);
                        break;

                    default:
                        break;
                }
            }
        };
        this.shareChartIv.setOnClickListener(moreClick);
        this.userSignRg
                .setOnCheckedChangeListener(new OnCheckedChangeListener() {

                    @Override
                    public void onCheckedChanged(RadioGroup group, int checkedId) {
                        switch (checkedId) {
                            case R.id.rb_user_sign_total:
                                signTotalData = new ArrayList<Map<String, Object>>();
                                // totalLayout.setVisibility(0);
                                totalTableRb.setChecked(true);
                                signHg.setVisibility(8);
                                shareChartIv.setVisibility(8);
                                detailLayout.setVisibility(8);
                                tipTv.setVisibility(8);
                                requestUserSignTotalData();
                                break;
                            case R.id.rb_user_sign_detail:
                                totalLayout.setVisibility(8);
                                tipTv.setVisibility(8);
                                // detailLayout.setVisibility(0);
                                requestUserSignDetailData();
                                break;

                            default:
                                break;
                        }
                    }
                });
        this.signTotalRg
                .setOnCheckedChangeListener(new OnCheckedChangeListener() {

                    @Override
                    public void onCheckedChanged(RadioGroup group, int checkedId) {
                        switch (checkedId) {
                            case R.id.rb_user_sign_table:
                                tableLayout.setVisibility(0);
                                signHg.setVisibility(8);
                                shareChartIv.setVisibility(8);
                                break;
                            case R.id.rb_user_sign_chart:
                                tableLayout.setVisibility(8);
                                signHg.setVisibility(0);
                                shareChartIv.setVisibility(0);
                                break;

                            default:
                                break;
                        }
                    }
                });
    }

    /**
     * 获取传递的参数
     */
    private void getBundle() {
        Intent intent = getIntent();
        userId = intent.getStringExtra("userId");
    }

    /**
     * 获取用户签到统计数据
     */
    private void requestUserSignTotalData() {
        AsyncLoadData ald = new AsyncLoadData(this, "加载中...",
                new AsyncAction() {

                    @Override
                    public void doLoad() throws Exception {
                        // 获取提交参数
                        Map<String, Object> nearbyBusinessParamMap = new HashMap<String, Object>();
                        nearbyBusinessParamMap.put("userId", userId);
                        // 发送请求
                        byte[] bSignTotal = HttpUtil.requestByPost(
                                UserSignedActivity.this,
                                Constants.USER_SIGN_TOTAL_API,
                                nearbyBusinessParamMap);
                        if (bSignTotal != null) {
                            parseSignTotalJson(bSignTotal);
                        }
                    }

                    @Override
                    public void loadEnd() throws Exception {
                        if (signTotalData.size() > 0) {
                            tipTv.setVisibility(8);
                            // 显示统计表格
                            totalLayout.setVisibility(0);
                            tableLayout.setVisibility(0);
                            setSignTotalAdapter();
                        } else {
                            tipTv.setVisibility(0);
                            totalLayout.setVisibility(8);
                            tableLayout.setVisibility(8);
                        }
                    }

                });
        ald.execute(0);
    }

    /**
     * 获取用户签到详情数据
     */
    private void requestUserSignDetailData() {
        AsyncLoadData ald = new AsyncLoadData(this, "加载中...",
                new AsyncAction() {

                    @Override
                    public void doLoad() throws Exception {
                        // 获取提交参数
                        Map<String, Object> nearbyBusinessParamMap = new HashMap<String, Object>();
                        nearbyBusinessParamMap.put("userId", userId);
                        nearbyBusinessParamMap.put("pageCnt", 1);
                        nearbyBusinessParamMap.put("pageRow", 30);
                        // 发送请求
                        byte[] bSignTotal = HttpUtil.requestByPost(
                                UserSignedActivity.this,
                                Constants.USER_SIGN_DETAIL_API,
                                nearbyBusinessParamMap);
                        if (bSignTotal != null) {
                            String jsonStr = new String(bSignTotal, "UTF-8");
                            Map<String, Object> test = JSON.parseObject(
                                    jsonStr,
                                    new TypeReference<Map<String, Object>>() {
                                    });
                            userSignList = JSON.parseArray(
                                    test.get("commentsList").toString(),
                                    UserSignDetialEntity.class);
                        }
                    }

                    @Override
                    public void loadEnd() throws Exception {
                        if (userSignList != null && userSignList.size() > 0) {
                            tipTv.setVisibility(8);
                            detailLayout.setVisibility(0);
                            setSignListAdapter();
                        } else {
                            tipTv.setVisibility(0);
                            detailLayout.setVisibility(8);
                        }
                    }

                });
        ald.execute(0);
    }

    /**
     * 调用签到详情列表适配器
     */
    public void setSignListAdapter() {
        if (CollectionUtil.UnNullAndZero(userSignList)) {
            this.userSignListAdapter = new UserSignListAdapter(this);
            this.userSignListAdapter.addItems(userSignList);
            this.signDetailLv.setFooterDividersEnabled(false);
            this.signDetailLv.setAdapter(userSignListAdapter);
        }
    }

    private void parseSignTotalJson(byte[] resultByte) {
        try {
            JSONObject jsonObj = new JSONObject(new String(resultByte, "UTF-8"));
            JSONArray stJsonArray = new JSONArray(
                    jsonObj.getString("resultList"));
            for (int i = 0, iLen = stJsonArray.length(); i < iLen; i++) {
                JSONObject stJson = stJsonArray.getJSONObject(i);
                Map<String, Object> curGroupMap = new HashMap<String, Object>();
                curGroupMap.put(G_KEY, stJson.getString("group_key"));
                curGroupMap.put(G_VAL, stJson.getString("group_val"));
                List<Map<String, String>> children = new ArrayList<Map<String, String>>();
                JSONArray stChildJsonArray = stJson.getJSONArray("child_data");
                for (int j = 0, jLen = stChildJsonArray.length(); j < jLen; j++) {
                    JSONObject stChildJson = stChildJsonArray.getJSONObject(j);
                    Map<String, String> curChildMap = new HashMap<String, String>();
                    curChildMap.put(C_KEY, stChildJson.getString("child_key"));
                    curChildMap.put(C_VAL, stChildJson.getString("child_val"));
                    children.add(curChildMap);
                }
                curGroupMap.put(G_CHILD, children);
                signTotalData.add(curGroupMap);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private void setSignTotalAdapter() {
        // 设置表格Adapter
        adapter = new ExAdapter(UserSignedActivity.this);
        exList = (ExpandableListView) findViewById(R.id.elv_user_sign_total);
        exList.setAdapter(adapter);
        exList.setGroupIndicator(null);
        exList.setDivider(null);
        // 设置图表数据
        signHg.setData(signTotalData);
        // 求最大值
        int max = Integer.parseInt(signTotalData.get(0).get(G_VAL).toString());
        for (int i = 0, len = signTotalData.size(); i < len; i++) {
            int temp = Integer.parseInt(signTotalData.get(i).get(G_VAL)
                    .toString());
            max = temp > max ? temp : max;
        }
        // Y轴大刻度间隔数
        int yC = 5;
        // 增加最大浮动值
        max += 5;
        // 让最大值都可以让间隔数整除
        if (max % yC != 0) {
            int temp = max / yC;
            max = (temp + 1) * yC;
        }
        signHg.init(0, max, 5, 13);
    }

    class ExAdapter extends BaseExpandableListAdapter {
        UserSignedActivity exlistview;

        public ExAdapter(UserSignedActivity elv) {
            super();
            exlistview = elv;
        }

        public View getGroupView(int groupPosition, boolean isExpanded,
                View convertView, ViewGroup parent) {
            View view = convertView;
            if (view == null) {
                LayoutInflater inflater = LayoutInflater
                        .from(UserSignedActivity.this);
                view = inflater.inflate(R.layout.user_sign_expand_group, null);
            }
            TextView title = (TextView) view
                    .findViewById(R.id.tv_user_sign_group_class);
            title.setText(signTotalData.get(groupPosition).get(G_KEY)
                    .toString());
            TextView count = (TextView) view
                    .findViewById(R.id.tv_user_sign_group_count);
            count.setText(signTotalData.get(groupPosition).get(G_VAL)
                    .toString());
            ImageView image = (ImageView) view
                    .findViewById(R.id.iv_user_sign_group_arrow);
            if (isExpanded) {
                image.setImageResource(R.drawable.arrow4);
            } else {
                image.setImageResource(R.drawable.arrow1);
            }
            View lineV = view.findViewById(R.id.v_user_sign_group_line);
            if (groupPosition == getGroupCount() - 1) {
                lineV.setVisibility(8);
            } else {
                lineV.setVisibility(0);
            }
            return view;
        }

        public long getGroupId(int groupPosition) {
            return groupPosition;
        }

        public Object getGroup(int groupPosition) {
            return signTotalData.get(groupPosition).get(G_KEY).toString();
        }

        public int getGroupCount() {
            return signTotalData.size();

        }

        // **************************************
        public View getChildView(int groupPosition, int childPosition,
                boolean isLastChild, View convertView, ViewGroup parent) {
            View view = convertView;
            if (view == null) {
                LayoutInflater inflater = LayoutInflater
                        .from(UserSignedActivity.this);
                view = inflater.inflate(R.layout.user_sign_expand_child, null);
            }
            List<Map<String, String>> childDate = (List<Map<String, String>>) signTotalData
                    .get(groupPosition).get(G_CHILD);
            TextView title = (TextView) view
                    .findViewById(R.id.tv_user_sign_child_class);
            title.setText(childDate.get(childPosition).get(C_KEY).toString());
            TextView count = (TextView) view
                    .findViewById(R.id.tv_user_sign_child_count);
            count.setText(childDate.get(childPosition).get(C_VAL).toString());
            LinearLayout childLayout = (LinearLayout) view
                    .findViewById(R.id.ll_user_sign_child_layout);
            if (isLastChild && groupPosition == getGroupCount() - 1) {
                childLayout
                        .setBackgroundResource(R.drawable.expand_child_bg_style);
            } else {
                childLayout.setBackgroundResource(R.color.user_sign_bg3);
            }
            return view;
        }

        public long getChildId(int groupPosition, int childPosition) {
            return childPosition;
        }

        public Object getChild(int groupPosition, int childPosition) {
            List<Map<String, String>> childDate = (List<Map<String, String>>) signTotalData
                    .get(groupPosition).get(G_CHILD);
            return childDate.get(childPosition).get(C_KEY).toString();
        }

        public int getChildrenCount(int groupPosition) {
            List<Map<String, String>> childDate = (List<Map<String, String>>) signTotalData
                    .get(groupPosition).get(G_CHILD);
            return childDate.size();
        }

        // **************************************
        public boolean hasStableIds() {
            return true;
        }

        public boolean isChildSelectable(int groupPosition, int childPosition) {
            return true;
        }

    }
}
